package com.goal98.team.controllers

import com.goal98.team.domain.Team
import com.goal98.team.domain.Person

class InfoController {

    def index = { }

    def myteamService
    def emailerService
    def activityService

    def teamCloud = {

        def teamList = Team.list(sort:"dateCreated", order:"asc", max:8)
        final def teamValueMap = buildTeamValueMap(teamList)
        return [teamValueMap: teamValueMap]
    }

    def playerCloud = {
        String teamName = params.selectedTag
        def team = Team.findByName(teamName, [cache: true])
        final def playerValueMap = buildplayerValueMap(team.members)
        return [playerValueMap: playerValueMap, teamInstance: team]
    }

    def showPlayer = {
        String playerTag = params.selectedTag
        def id = playerTag?.split("-")[0]

        def person = Person.get(id)
        if (!person) {
            flash.message = "Person not found with id $params.id"
            redirect action: list
            return
        }

        List roleNames = []
        for (role in person.authorities) {
            roleNames << role.description
        }
        roleNames.sort {n1, n2 ->
            n1 <=> n2
        }

        [person: person, roleNames: roleNames]
    }

    def buildTeamValueMap(def teamList) {
        def result = [:]
        teamList.each {Team team ->
            result[team.name] = team.members.size()
        }
        return result
    }

    def buildplayerValueMap(def playerList) {
        def result = [:]
        playerList.each {Person player ->
            result["${player.id}-${player.userRealName}"] = player.username.size()
        }
        return result
    }


    def pendingTask = {
        final def myteam = myteamService.getMyteam()
        def upcomingActivity = activityService.getUpcomingActivity(myteam)
        def pendingActivity = activityService.getPendingActivities(myteam)
        def pendingMember = myteamService.playersInMyTeam().findAll {Person player ->
            player.account?.balance < 30 || !player.account
        }
        def model = [
                activityList: pendingActivity,
                memberList: pendingMember,
                upcomingActivity: upcomingActivity]

        def view = 'pendingTask'

        if (session.mobile)
            view = 'm-' + view

        render(view: view, model: model)
    }

    def testMail = {
        final def html = g.render(template: '/email/registrationInfo', model: [request: request, person: [Person.get(1)]])
        emailerService.sendTestMail(
                html)
        render html
    }
}
